package org.example.multi_sys_consist.module.impl;

import com.alibaba.fastjson.JSONObject;
import org.example.multi_sys_consist.constant.TransactionJobType;
import org.example.multi_sys_consist.module.TransactionJobExecutor;
import org.example.multi_sys_consist.pojo.entity.TransactionJob;
import org.example.multi_sys_consist.remote.WorkflowService;
import org.example.multi_sys_consist.service.TodoService;
import org.example.multi_sys_consist.service.TransactionJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static org.example.multi_sys_consist.constant.TransactionJobType.UPDATE_TODO;

@Component
public class UpdateTodoExecutor implements TransactionJobExecutor {

    @Autowired
    private TodoService todoService;
    @Autowired
    private WorkflowService workflowService;
    @Autowired
    private TransactionJobService transactionJobService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(TransactionJob job) {
        JSONObject jo = JSONObject.parseObject(job.getData());
        List<Long> todoList = workflowService.getTodoList(jo.getString("workflowId"));
        if (todoList != null && todoList.size() > 0) {
            todoService.save(jo.getLong("applyId"), todoList);
        } else {
            //留下生成财务日志的任务
            JSONObject data = new JSONObject();
            data.put("applyId", jo.getLong("applyId"));
            transactionJobService.create(TransactionJobType.CREATE_FINANCE_LOG, data);
        }
    }

    @Override
    public TransactionJobType type() {
        return UPDATE_TODO;
    }
}
